package com.wdy.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RegexUtils;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public Result signCount() {
        //1.获取当前登录用户
        Long userId = UserHolder.getUser().getId();

        //2.获取当前时间
        LocalDateTime now = LocalDateTime.now();

        //3.拼接key
        String key = "sign:" + userId + ":" + now.format(DateTimeFormatter.ofPattern("yyyyMM"));

        int day = now.getDayOfMonth();
        List<Long> result = stringRedisTemplate.opsForValue().bitField(key,
                BitFieldSubCommands.create()
                        .get(BitFieldSubCommands.BitFieldType.unsigned(day - 1))
                        .valueAt(0));
        if (result == null || result.isEmpty()) {
            return Result.ok(0);
        }
        int sign = result.get(0).intValue();
        int count = 0;
        while (sign != 0) {
            if(0==(sign & 1)){
                break;
            }else {
                count++;
            }
            sign = sign >>> 1;
        }
        return Result.ok(count);
    }

    @Override
    public Result sign() {
        //1.获取当前登录用户
        Long userId = UserHolder.getUser().getId();

        //2.获取当前时间
        LocalDateTime now = LocalDateTime.now();

        //3.拼接key
        String key = "sign:" + userId + ":" + now.format(DateTimeFormatter.ofPattern("yyyyMM"));

        //4.签到
        int day = now.getDayOfMonth();
        stringRedisTemplate.opsForValue().setBit(key, day - 1, true);

        return Result.ok();
    }

    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {
        //1.校验手机号和验证码
        if (RegexUtils.isPhoneInvalid(loginForm.getPhone())) {
            //2.校验失败,返回错误信息
            return Result.fail("手机号格式错误");
        }
        String sessionCode = stringRedisTemplate.opsForValue().get("login:code:"+loginForm.getPhone());
        if(sessionCode==null||!sessionCode.equals(loginForm.getCode())){
            //2.校验失败,返回错误信息
            return Result.fail("验证码错误");
        }

        //3.校验成功,根据手机号查询用户
        User user = query().eq("phone", loginForm.getPhone()).one();

        //4.用户不存在,注册新用户
        if (user == null) {
            user=new User();
            user.setPhone(loginForm.getPhone());
            user.setNickName("user_"+RandomUtil.randomString(10));
            save( user);
        }

        //5.用户存在或者创建了一个新用户,返回用户信息
        String token = UUID.randomUUID().toString(true);
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        stringRedisTemplate.opsForHash().putAll("login:token:"+token,
                BeanUtil.beanToMap(userDTO,new HashMap<>(),
                        CopyOptions.create().setFieldValueEditor((fieldName,value)->value.toString())));
        stringRedisTemplate.expire("login:token:"+token,30,TimeUnit.MINUTES);
        return Result.ok(token);
    }

    @Override
    public Result sendCode(String phone, HttpSession session) {
        //1.校验手机号
        if (RegexUtils.isPhoneInvalid(phone)) {
            //2.校验失败,返回错误信息
            return Result.fail("手机号格式错误");
        }
        //3.校验成功,生成验证码
        String code = RandomUtil.randomNumbers(6);

        //4.保存验证码到redis
        stringRedisTemplate.opsForValue().set("login:code:"+phone, code,1, TimeUnit.MINUTES);

        //5.假装发送了验证码,返回ok
        log.debug("发送验证码成功,验证码:{}",code);
        return Result.ok();
    }
}
